<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\admin\controller\Base;
use think\Request;
use think\facade\Db;

/**
 * 客户控制器
 * @author  Bobo
 */
class Customer extends Base
{

    protected $request;
    protected $service;
    protected $validate;
    protected $operator_id;

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->service = new \app\admin\service\Customer();
        $this->validate = new \app\admin\validate\Customer();

        $this->operator_id = $request->operator_id;
    }

    /**
     * @describe 获取客户列表
     * @author: Bobo
     * @date: 2024-06-05 03:04:33
     * @param [] type
     * @return Renderable
     */
    public function index()
    {
        $params = empty($this->request->params) ? [] : $this->request->params;

        if (!$this->validate->scene('search')->check($params)) {
            return $this->returnJsonData(100001, [], $this->validate->getError());
        }

        $pageIndex         = isset($params['pageIndex'])             ? intval($params['pageIndex'])             : 1;
        $pageSize          = isset($params['pageSize'])              ? intval($params['pageSize'])              : 10;

        $cusname           = isset($params['cusname'])               ? trim($params['cusname'])               : null;
        $phone             = isset($params['phone'])               ? trim($params['phone'])               : null;
        $tripartiteChannelId = isset($params['tripartite_channel_id']) ? intval($params['tripartite_channel_id']) : null;
        $status            = isset($params['status'])                ? intval($params['status'])                : null;
        $stage             = isset($params['stage'])                 ? intval($params['stage'])                 : null;
        $cusnature         = isset($params['cusnature'])             ? intval($params['cusnature'])             : null;
        $remark            = isset($params['remark'])                ? trim($params['remark'])             : null;
        $createTime        = isset($params['create_time'])           ? trim($params['create_time'])             : null;
        $updateTime        = isset($params['update_time'])           ? trim($params['update_time'])             : null;
        $attr              = isset($params['attr'])                  ? intval($params['attr'])                  : 0; //属性： 1-私海  2-公海
        $role              = isset($params['role'])                  ? trim($params['role'])                    : null;
        $email              = isset($params['email'])                ? trim($params['email'])                    : null;
        $owner              = isset($params['owner'])                ? trim($params['owner'])                    : null;
        $partner              = isset($params['partner'])                ? trim($params['partner'])                    : null;
        $country_id         = isset($params['country_id'])            ? intval($params['country_id'])            : null;

        $where = ['is_del' => 0];

        if ($cusname) {
            $where[] = ['cusname', 'like', '%' . $cusname . '%'];
        }
        if ($phone) {
            $where[] = ['phone', 'like', '%' . $phone . '%'];
        }
        if ($email) {
            $where[] = ['email', 'like', '%' . $email . '%'];
        }
        if ($tripartiteChannelId) {
            $where['tripartite_channel_id'] = $tripartiteChannelId;
        }
        if ($status != NULL) {
            $where['status'] = $status;
        }
        if ($stage != NULL) {
            $where['stage'] = $stage;
        }
        if ($cusnature) {
            $where['cusnature'] = $cusnature;
        }

        if ($partner) {
            $where[] = ['partner', 'FIND IN SET', $partner];
        }
        if ($remark) {
            $where[] = ['remark', 'like', $remark . '%'];
        }
        if ($country_id) {
            $where['country_id'] = $country_id;
        }
        if ($createTime) {
            $start_create_time = explode(',', $createTime)[0] . ' 00:00:00';
            $end_create_time = explode(',', $createTime)[1] . ' 23:59:59';
            $where[] = ['create_time', 'between', [$start_create_time, $end_create_time]];
        }
        if ($updateTime) {
            $start_update_time = explode(',', $updateTime)[0] . ' 00:00:00';
            $end_update_time = explode(',', $updateTime)[1] . ' 23:59:59';
            $where[] = ['update_time', 'between', [$start_update_time, $end_update_time]];
        }

        if ($role) {
            if ('distributor' == $role) {
                $where['role'] = 'distributor'; // 经销商
            }
        }

        $field = 'id,cusname,phone,email,tripartite_channel_id,tripartite_account,nickname,country_id,status,stage,tags,owner,partner,custype,cusnature,source,company_name,remark,is_login,login_num,last_login_time,last_ip,login_status,role,is_advance,create_time,update_time';


        $res =  $this->service->getList($pageIndex, $pageSize, $where, $field, $attr,$owner, $this->operator_id);

        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe 获取客户列表
     * @author: Bobo
     * @date: 2024-06-05 03:04:33
     * @param [] type
     * @return Renderable
     */
    public function discountList()
    {
        $params = empty($this->request->params) ? [] : $this->request->params;
        $pageIndex         = isset($params['pageIndex'])             ? intval($params['pageIndex'])             : 1;
        $pageSize          = isset($params['pageSize'])              ? intval($params['pageSize'])              : 10;
        $cusname           = isset($params['cusname'])               ? trim($params['cusname'])               : null;
        $phone             = isset($params['phone'])               ? trim($params['phone'])               : null;
        $where = ['is_del' => 0];
        $where[] = ['role', '<>', 'distributor'];

        if ($cusname) {
            $where[] = ['cusname', 'like', '%' . $cusname . '%'];
        }
        if ($phone) {
            $where[] = ['phone', 'like', '%' . $phone . '%'];
        }
        $res =  $this->service->getListFotDiscount($pageIndex, $pageSize, $where);

        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe 获取客户详情
     * @author: Bobo
     * @date: 2024-06-05 03:07:37
     * @param [int] $id 客户ID @required
     * @return Renderable
     */
    public function show()
    {
        $params = $this->request->params;
        if (!$this->validate->scene('show')->check($params)) {
            return $this->returnJsonData(100001, [], $this->validate->getError());
        }
        $id = intval($params['id']);
        $field = 'id,cusname,phone,email,tripartite_channel_id,tripartite_account,nickname,country_id,status,stage,tags,loss,owner,custype,cusnature,source,company_name,remark,is_login,login_num,last_login_time,last_ip,login_status,city,partner,create_time,update_time,creator,updater,att_path,last_followtime,is_advance,role';
        $res  = $this->service->getOneById($id, $field, $this->operator_id);
        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe 创建客户
     * @author: Bobo
     * @date: 2024-06-05 03:09:17
     * @param [array] $data 创建客户的数据 @required
     * @return Renderable
     */
    public function create()
    {
        $params = $this->request->params;
        if (!$this->validate->scene('create')->check($params)) {
            return $this->returnJsonData(100001, null, $this->validate->getError());
        }
        $params['creator'] = $this->operator_id;
        $params['partner'] = implode(',', $params['partner']);
        if (isset($params['att_path']) && is_array($params['att_path'])) {
            $params['att_path'] = implode(',', $params['att_path']);
        }
        $res  = $this->service->create($params);
        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * 更新客户
     * @describe 更新客户
     * @author: Bobo
     * @date: 2024-06-05 03:11:17
     * @param [int] $id 客户ID @required
     * @param [array] $data 更新客户的数据 @required
     * @return Renderable
     */
    public function update()
    {
        $params = $this->request->params;
        if (!$this->validate->scene('update')->check($params)) {
            return $this->returnJsonData(100001, [], $this->validate->getError());
        }
        $params['updater'] = $this->operator_id;
        $params['update_time'] = date('Y-m-d H:i:s', time());
        $params['partner'] = implode(',', $params['partner']);

        if (is_array($params['att_path'])) {
            $params['att_path'] = implode(',', $params['att_path']);
        }

        return json($this->service->update($params));
    }


    /**
     * @describe 删除客户
     * @author: Bobo
     * @date: 2024-06-05 03:13:56
     * @param [int] $id 客户ID @required
     * @return Renderable
     */
    public function delete()
    {
        $params = $this->request->params;
        if (!$this->validate->scene('delete')->check($params)) {
            return $this->returnJsonData(100001, [], $this->validate->getError());
        }
        $ids =  trim($params['ids']);
        $res = $this->service->batchLogicalDelete($ids);
        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }


    /**
     * @describe 分配公海客户
     * @author: Bobo
     * @date: 2024-07-05 14:14:02
     * @param [type] @required
     * @return Renderable
     */
    public function allocationPublicCustomer()
    {
        $params = $this->request->params;

        if (!$this->validate->scene('allocation')->check($params)) {
            return $this->returnJsonData(100001, [], $this->validate->getError());
        }

        $conditon = ['id' => $params['allocationId']];
        $update = ['owner' => $params['id'], 'updater' => $this->operator_id, 'update_time' => date('Y-m-d H:i:s'), 'allocate_time' => date('Y-m-d H:i:s')];
        $res = $this->service->operatorCustomer(4, $conditon, $update, intval($params['allocationId']));

        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe 捞取公海客户
     * @author: Bobo
     * @date: 2024-07-05 14:20:07
     * @param [type] @required
     * @return Renderable
     */
    public function fishingPublicCustomer()
    {
        $params = $this->request->params;

        if (!isset($params['id'])) {
            return $this->returnJsonData(100001, [], " The 'id' parameter is required.");
        }

        if (!$this->validate->scene('show')->check($params)) {
            return $this->returnJsonData(100001, [], $this->validate->getError());
        }
        $conditon = ['id' => $params['id']];
        $update = ['owner' => $this->operator_id, 'updater' => $this->operator_id, 'update_time' => date('Y-m-d H:i:s'), 'allocate_time' => date('Y-m-d H:i:s')];
        $res = $this->service->operatorCustomer(3, $conditon, $update, $params['id']);

        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe 退回客户到公海
     * @author: Bobo
     * @date: 2024-07-11 14:19:54
     * @param [type] @required
     * @return Renderable
     */
    public function returnPublic()
    {
        $params = $this->request->params;
        if (!isset($params['id'])) {
            return $this->returnJsonData(100001, [], " The 'id' parameter is required.");
        }

        if (!$this->validate->scene('show')->check($params)) {
            return $this->returnJsonData(100001, [], $this->validate->getError());
        }

        $conditon = ['id' => $params['id']];
        $update = ['owner' => 0, 'partner' => '', 'updater' => $this->operator_id, 'update_time' => date('Y-m-d H:i:s'), 'allocate_time' => null];
        $res = $this->service->operatorCustomer(5, $conditon, $update, $params['id']);

        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2024-07-23 10:33:18
     * @param [type] @required
     * @return Renderable
     */
    public function getFieldEnum()
    {
        $params = $this->request->params;
        $res = $this->service->getFieldEnum($params['field']);
        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    public function getSelect(Request $request)
    {
        $params = empty($this->request->params) ? [] : $this->request->params;
        $role           = isset($params['role'])               ? trim($params['role'])               : null;
        $cusname           = isset($params['cusname'])               ? trim($params['cusname'])               : null;
        if ($role) {        // 订单中查询经销商或者客户接口
            if ('distributor' == $role) {
                $where['role'] = 'distributor'; // 经销商
            }
        }
        $where = [];
        if ($cusname) {
            $where['cusname'] = $cusname;
        }

        $res = $this->service->getSelect($where, "id AS value, concat( ifnull(cusname,''),' (',ifnull(email,''),') ')   as label", $this->operator_id);
        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-02-10 14:58:37
     * @param [type] @required
     * @return Renderable
     */
    public function getOperationLog()
    {
        $params = $this->request->params;
        if (!$this->validate->scene('operation')->check($params)) {
            return $this->returnJsonData(100001, [], $this->validate->getError());
        }

        $pageIndex         = isset($params['pageIndex'])             ? intval($params['pageIndex'])             : 1;
        $pageSize          = isset($params['pageSize'])              ? intval($params['pageSize'])              : 100;
        $id                = isset($params['id'])                    ? intval($params['id'])               : 0;
        $where             = [];
        if ($id > 0) {
            $where['c_id'] = $id;
        } else {
            return $this->returnJsonData(100001, [], "缺少参数");
        }

        $res =  $this->service->getOperationLogList($pageIndex, $pageSize, $where, $field = 'id,operate,c_id,msg,operate_id,operate_name,create_time');

        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe 审批记录
     * @author: Bobo
     * @date: 2025-03-03 15:06:38 
     * @param [type] @required
     * @return Renderable
     */
    public function getApprovalRecords()
    {
        $params = $this->request->params;
        if (!$this->validate->scene('approvalRecords')->check($params)) {
            return $this->returnJsonData(100001, [], $this->validate->getError());
        }

        $pageIndex         = isset($params['pageIndex'])             ? intval($params['pageIndex'])             : 1;
        $pageSize          = isset($params['pageSize'])              ? intval($params['pageSize'])              : 100;
        $id                = isset($params['id'])                    ? intval($params['id'])                    : 0;
        $where             = [];
        if ($id > 0) {
            $where['id'] = $id;
        } else {
            return $this->returnJsonData(100001, [], "缺少参数");
        }

        $res =  $this->service->getApprovalRecords($pageIndex, $pageSize, $where, $field = 'user_id,business_module,entity_id');

        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe 设置客户角色
     * @author: Bobo
     * @date: 2025-06-23 10:33:18
     * @param [type] @required
     * @return Renderable
     */
    public function role()
    {
        $params = $this->request->params;
        if (!$this->validate->scene('role')->check($params)) {
            return $this->returnJsonData(100001, [], $this->validate->getError());
        }
        $params['updater'] = $this->operator_id;
        $params['update_time'] = date('Y-m-d H:i:s');
        $res = $this->service->role($params);
        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }
}
